package Q2.dao.impl;

import Q2.dao.StudentDao;
import Q2.pojo.Student;
import lombok.AllArgsConstructor;
import lombok.NonNull;
import utils.BeanUtils;
import utils.PersistenceUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Map;

@AllArgsConstructor
public class StudentDaoH2Impl implements StudentDao {

    /**
     * A connection (session) with a specific database
     */
    private final Connection conn;

    @Override
    public boolean insertOne(@NonNull Student student) {
        final StringBuilder keyPart = new StringBuilder(25);
        final StringBuilder valuePart = new StringBuilder(25);
        final String tableName = PersistenceUtils.getTableName(student.getClass());
        final Map<String, Object> properties = BeanUtils.objectToMap(student);
        final ArrayList<String> keys = new ArrayList<>(properties.keySet());

        // 键和数据部分拼接
        keys.forEach(key -> {
            keyPart.append(key).append(',');
            valuePart.append('?').append(',');
        });

        // 删除末尾的 ','
        keyPart.deleteCharAt(keyPart.length() - 1);
        valuePart.deleteCharAt(valuePart.length() - 1);

        final String SQL = String.format("insert into %s(%s) values(%s)", tableName, keyPart, valuePart);
        try (final PreparedStatement pstmt = conn.prepareStatement(SQL)) {
            // 值的设定
            for (int i = 1; i < keys.size() + 1; i++) {
                pstmt.setObject(i, properties.get(keys.get(i - 1)));
            }

            return pstmt.executeUpdate() > 1;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean deleteByPrimaryKey(int id) {
        

        return false;
    }

    @Override
    public boolean updateByPrimaryKey(@NonNull Student student) {
        return false;
    }

    @Override
    public Student findByStudentNumber(@NonNull String number) {
        return null;
    }

    public static void main(String[] args) {
        final String tableName = PersistenceUtils.getTableName(Student.class);
        System.out.println(tableName);
    }

}
